package com.group.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.alibaba.fastjson.JSONObject;
import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.group.model.ActionLog;
import com.group.model.ExceptionMsg;
import com.group.model.FileMap;
import com.group.util.NoteException;
import com.group.util.WeiXinConf;
import com.group.util.WeiXinUtils;

import sun.misc.BASE64Decoder;

/**
 * 通用的逻辑
 * 
 * @author zhaolei
 *
 */
@Controller
public class GeneralController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(GeneralController.class);

	/**
	 * 记录页面日志
	 * 
	 * @param actionLog
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/tracking", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult tracking(@RequestBody ActionLog actionLog, HttpServletRequest request) {
		// 设置sessionId
		actionLog.setSessionId(request.getSession().getId());

		beanDao.save(actionLog);

		return new BaseResult();
	}

	/**
	 * 下载文件
	 * @param fileId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/file/download", method = RequestMethod.GET)
	public void getFile(String fileId, HttpServletResponse response) throws Exception {
		validChar(fileId);

		FileMap fm = beanDao.quickQueryOne(FileMap.class, "fileId", fileId);
		String filename = fileId;
		if (fm != null)
			filename = fm.getFilename();

		response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(filename, "utf-8"));
		// response.setContentType(urlCon.getContentType());

		File file = weiXinUtils.getImage(fileId);

		try {
			FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
		} catch (Exception e) {
			throw new NoteException("文件不存在");
		}
	}

	/**
	 * 上传图片接口,返回fileId
	 * 
	 * @param request
	 * @param width
	 *            文件长
	 * @param height
	 *            文件宽
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/file/upload")
	@ResponseBody
	public GeneralResult<String> upload(HttpServletRequest request, Integer width, Integer height) throws Exception {

		// 获得文件单个上传文件：
		MultipartFile file = getFile((MultipartRequest) request);

		if (file.getOriginalFilename() == null) {
			throw new NoteException("上传文件名(OriginalFilename)不能为空");
		}

		if (file.getOriginalFilename().endsWith("webp"))
			throw new NoteException("对不起,不支持webp图片");
		String fileId = WeiXinUtils.saveTo(file.getInputStream(), file.getOriginalFilename(), WeiXinConf.IMAGE_DIR);

		FileMap fm = new FileMap();
		fm.setFileId(fileId);
		fm.setHeight(height);
		fm.setWidth(width);
		fm.setFilename(file.getOriginalFilename());
		beanDao.save(fm);

		return new GeneralResult<String>().setValue(fileId);
	}

	/**
	 * 发送邮件
	 * 
	 * @param fileId
	 * @param emailAddress
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/file/email")
	@ResponseBody
	public BaseResult emailFile(String fileId, String emailAddress) throws Exception {
		File file = weiXinUtils.getImage(fileId);
		if (file.exists()) {
			List<File> files = new ArrayList<File>();
			files.add(file);
			weiXinUtils.sendEmailAttachFile(files, emailAddress);
		}

		return new BaseResult();
	}

	/**
	 * 测试数据库连通性
	 * 
	 * @return
	 */
	@RequestMapping("/test")
	@ResponseBody
	public BaseResult test() {
		ExceptionMsg msg = new ExceptionMsg();
		msg.setRequestStr("request");
		msg.setBody("test - body ");
		beanDao.save(msg);
		return new BaseResult();
	}

	/**
	 * 获取token
	 * 
	 * @return
	 */
	@RequestMapping("/wx/token")
	@ResponseBody
	public GeneralResult<String> getToken() {

		return new GeneralResult<String>().setValue(weiXinUtils.getToken());
	}

	/**
	 * 上传base64图片
	 * 
	 * @param para
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadBase64")
	@ResponseBody
	public GeneralResult<String> uploadBase64(@RequestBody JSONObject para) throws Exception {
		String imgStr = para.getString("base64Url");
		String suffix = para.getString("suffix");

		if (imgStr.contains(","))
			imgStr = imgStr.substring(imgStr.indexOf(",") + 1);
		BASE64Decoder decoder = new BASE64Decoder();
		// Base64解码
		byte[] b = decoder.decodeBuffer(imgStr);
		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {// 调整异常数据
				b[i] += 256;
			}
		}

		String fileId = WeiXinUtils.saveTo(new ByteArrayInputStream(b), "h5页面上传图片." + suffix, WeiXinConf.IMAGE_DIR);
		return new GeneralResult<String>().setValue(fileId);
	}

	/**
	 * 查询系统参数
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping("/systempara/get")
	@ResponseBody
	public GeneralResult<String> getSystempara(String name) {

		return new GeneralResult<String>().setValue(getSystemParaValue(name));
	}

}
